package com.eazy.lksy.web.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.eazy.lksy.web.model.LineName;
import com.eazy.lksy.web.view.vo.RequestLineName;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.eazy.lksy.web.core.dao.BaseDao;
import com.eazy.lksy.web.utils.StrKit;

@Repository
public class LineDao extends BaseDao {

	/**
	 * 查询线路名称
	 */
	public List<LineName> selectLineName(RequestLineName request) {
		String sql = "select lne.`id`,c.`name` cityName,lne.`name`,DATE_FORMAT(lne.create_time,'%Y-%m-%d') create_time,lne.city_id FROM city c INNER JOIN line_name lne ON c.`id` = lne.`city_id` where 1=1  order by c.id asc";

		RowMapper<LineName> rowMapper = BeanPropertyRowMapper.newInstance(LineName.class);
		List<LineName> lineNames = dao.query(sql,rowMapper);

		if(StrKit.notEmpty(request.getCityid())) {
			lineNames = lineNames.stream().filter(line -> line.getCityId().equals(request.getCityid())).collect(Collectors.toList());
		}
		if(StrKit.notEmpty(request.getBegintime()) && StrKit.notEmpty(request.getEndtime())) {
			try {
				Date beginTime =  DateUtil.parse(request.getBegintime(), "yyyy-MM-dd");
					Date endTime =  DateUtil.parse(request.getEndtime(), "yyyy-MM-dd");
				lineNames = lineNames.stream().filter(line -> line.getCreateTime().before(beginTime) &&
						line.getCreateTime().after(endTime)).collect(Collectors.toList());
			}catch (Exception e) {

			}
		}
		return lineNames;
	}
	
	public List<Map<String, Object>> selectLine(String city_id) {
		String sql = "select * from line_name where city_id=?";
		return dao.queryForList(sql,city_id);
	}
	
	/**
	 * 删除线路
	 */
	public void deleteLine(String line_id) {
		String sql = "delete from line_name where id=?";
		dao.update(sql, line_id);
	}
	
	/**
	 * 查看线路是否存在
	 */
	public boolean isExists(String city_id,String line_name) {
		String sql = "SELECT * FROM line_name  where city_id=? and name=?";
		Map<String,Object> result = queryForMap(sql, city_id,line_name);
		return result != null ? false : true;
	}


	/**
	 * 添加线路
	 */
	public void addLineName(Map<String,String> map) {
		String sql = "insert into line_name(name,city_id) values(?,?)";
		dao.update(sql, map.get("name"),map.get("cityid"));
	}
	
	/**
	 * 修改线路
	 */
	public void updateLineName(Map<String,String> map) {
		String sql = "update line_name set name=?,city_id=? where id=?";
		dao.update(sql, map.get("name"),map.get("cityid"),map.get("id"));
	}
}
